# coding=utf-8
import os
import re
import time


# C:\Users\Administrator\AppData\Local\Programs\Python\Python37\Lib\site-packages\pyqt5_tools\Qt\bin\designer.exe

# 读文件

# \[[\d\w" _=\.\(\),]*\]

def read_file(read_file_path):
    with open(read_file_path, 'rb') as f:
        lines = f.read()
    return lines


# 处理内容
def context_trim(lines, reg, rep):
    out = re.sub(reg, rep, lines)
    return out


# 写入文件
def write_file(encoding_type, out, read_file_path):
    # 写入文件名
    filepath, tmpfilename = os.path.split(read_file_path)
    time_String = time.strftime("%Y%m%d-%H%M%S", time.localtime())
    # 创建文件夹
    folder = os.path.exists('./display')
    if not folder:
        os.makedirs('./display')
    write_file_path = './display/' + \
                      tmpfilename.split('.')[0] + '(' + time_String + ')' + '.txt'
    with open(write_file_path, mode='w', encoding=encoding_type) as f:
        f.write(out)
    print(write_file_path + '>>写入成功')


def get_all_path(open_file_path):
    rootdir = open_file_path
    path_list = []
    list = os.listdir(rootdir)  # 列出文件夹下所有的目录与文件
    for i in range(0, len(list)):
        com_path = os.path.join(rootdir, list[i])
        # print(com_path)
        if os.path.isfile(com_path):
            path_list.append(com_path)
        if os.path.isdir(com_path):
            path_list.extend(get_all_path(com_path))
    # print(path_list)
    return path_list


def run_run_run(file_list, display_encoding,
                reg_1, rep_1, reg_2, rep_2, reg_3, rep_3):
    msg = ""
    try:
        for txt_file in file_list:
            print('文件路径：', txt_file)
            context = read_file(txt_file)
            print("读取字节：", context)
            context = context.decode(display_encoding,"ignore")
            # print("转换为字符串：", context)

            if reg_1 != '':
                context = context_trim(context, reg_1, rep_1)
            if reg_2 != '':
                context = context_trim(context, reg_2, rep_2)
            if reg_3 != '':
                context = context_trim(context, reg_3, rep_3)
            write_file("utf-8", context, txt_file)
        msg = "处理完毕"
    except BaseException as e:
        msg = "ERROR:" + str(e)
        print(e)
    return msg
